package org.jeecg.modules.monitoring.j_monitoring.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.netty.util.internal.StringUtil;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.monitoring.j_monitoring.entity.MDocumentManagement;
import org.jeecg.modules.monitoring.j_monitoring.mapper.MDocumentManagementMapper;
import org.jeecg.modules.monitoring.j_monitoring.service.IMDocumentManagementService;
import org.jeecg.modules.monitoring.j_monitoring.vo.DocTreeNode;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.*;

/**
 * @Description: 文档管理
 * @Author: xiaoyq
 * @Date:   2023-06-26
 * @Version: V1.0
 */
@Service
public class MDocumentManagementServiceImpl extends ServiceImpl<MDocumentManagementMapper, MDocumentManagement> implements IMDocumentManagementService {


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(MDocumentManagement mDocumentManagement) {
		this.baseMapper.insert(mDocumentManagement);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(MDocumentManagement mDocumentManagement) {
		this.baseMapper.updateById(mDocumentManagement);

		//1.先删除子表数据

		//2.子表数据重新插入
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		baseMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			baseMapper.deleteById(id);
		}
	}

	@Override
	public List<DocTreeNode> searchByKeyWord(String keyWord, String parentId) {
		List<MDocumentManagement> dataList = this.getBaseMapper().queryByKeyWord(keyWord,parentId);
		List<DocTreeNode> arrayList = new ArrayList<>();

		List<DocTreeNode> resultList = new ArrayList<>();
		DocTreeNode model;
		DocTreeNode pNode;
		List<DocTreeNode> children;
		if(dataList.size() > 0) {
			Map<String, DocTreeNode> listMap = new HashMap(5);
			for(MDocumentManagement dataItem : dataList) {
				model = new DocTreeNode(dataItem);
				arrayList.add(model);
				listMap.put(model.getId(),model);
			}

			for(DocTreeNode treeNode : arrayList) {
				if(listMap.containsKey(treeNode.getPid())){
					pNode = listMap.get(treeNode.getPid());
					children = pNode.getChildren();
					if(children==null){
						children = new ArrayList<>();
						pNode.setChildren(children);
					}
					children.add(treeNode);
				}
				else{
					resultList.add(treeNode);
				}
			}
		}
		return resultList;
	}

}
